<template>
  <div class="add-wrapper">
    <el-page-header @back="goBack" :content="isAdd ? '创建BOM' : '编辑BOM'">
    </el-page-header>
    <div class="form-wrapper">
      <div class="top-form">
        <div class="descLabel">基本信息</div>
        <!-- @keyup.enter.native="dataFormSubmitHandle()" -->
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          @submit.native.prevent
          label-width="120px"
        >
          <el-form-item v-if="!isAdd" prop="bom_serial" label="BOM编号">
            <el-input v-model="dataForm.bom_serial" disabled></el-input>
          </el-form-item>
          <el-form-item prop="name" label="BOM名称">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <el-form-item prop="versions" label="版本">
            <el-input v-model="dataForm.versions" placeholder="1.0.0">
              <template slot="prepend">V</template>
            </el-input>
          </el-form-item>
          <el-form-item label="产品分类" prop="classify_ids">
            <el-cascader
              ref="classifyRef"
              :key="classifyIndex"
              @change="treeChange"
              v-model="dataForm.classify_ids"
              :options="classifyList"
              :props="{
                multiple: true,
                expandTrigger: 'hover',
                checkStrictly: true,
              }"
              placeholder="请选择"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item prop="product_info" label="产品规格">
            <el-cascader
              :key="productIndex"
              @change="handleChange"
              v-model="dataForm.product_info"
              :options="productList"
              :props="{ expandTrigger: 'hover' }"
              placeholder="请选择"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              placeholder="请输入"
              type="textarea"
              :rows="3"
              v-model="dataForm.remarks"
            >
            </el-input>
          </el-form-item>

          <el-form-item label="BOM配件">
            <el-button type="primary" @click="handleAdd">添加</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="size-form padTop20">
        <el-form @submit.native.prevent label-width="120px">
          <el-form-item label="">
            <el-table :data="generateList" border style="width: 100%">
              <el-table-column
                type="index"
                label="序号"
                header-align="center"
                align="center"
                width="80"
              ></el-table-column>
              <el-table-column
                prop="material_serial"
                label="物料编号"
                header-align="center"
                align="center"
                width="240"
              ></el-table-column>
              <el-table-column
                prop="name"
                label="物料名称"
                header-align="center"
                align="center"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="specifications_model"
                label="规格"
                header-align="center"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="parts_num"
                label-class-name="thRequired"
                label="配件数量"
                header-align="center"
                align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  <!-- v-model.number="scope.row.num" -->
                  <el-input
                    type="number"
                    placeholder="请输入"
                    v-model="scope.row.parts_num"
                    :min="1"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="price"
                label="价格（人民币）"
                header-align="center"
                align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-input
                    type="number"
                    placeholder="请输入"
                    v-model="scope.row.price"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="day"
                label="预期工期（天）"
                header-align="center"
                align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    type="number"
                    v-model="scope.row.day"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="daily_output"
                label="日产量（个）"
                header-align="center"
                align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    type="number"
                    v-model="scope.row.daily_output"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('handle')"
                fixed="right"
                header-align="center"
                align="center"
                width="150"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-bottom: 36px">
        <el-button @click="goBack" style="margin-left: 45%; margin-top: 36px"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="dataFormSubmitHandle()"
          style="margin-left: 21px"
          >确定</el-button
        >
      </div>
    </div>
    <el-backtop></el-backtop>
    <el-dialog :visible.sync="dialogVisible" title="查看">
      <img width="100%" :src="dialogImageUrl" class="avatar" />
    </el-dialog>
    <MaterialChoose
      v-if="addOrUpdateVisible"
      ref="bomFit"
      @handleClose="handleClose"
      @handleConfirm="fitConfirm"
    ></MaterialChoose>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import MaterialChoose from '@/components/material-choose'
import { tranSelectArr, transCascader } from '@/utils'
import { isVersion } from '@/utils/validate'
import {
  getBomDetail,
  addBom,
  getProductClassify,
  getProductList,
  deleteBomFit,
} from '@/api'
export default {
  components: {
    MaterialChoose,
  },
  data() {
    return {
      visible: false,
      dataForm: {
        id: '',
        name: '',
        versions: '',
        classify_ids: [],
        product_info: [],
        remarks: '',
      },
      dialogImageUrl: '',
      dialogVisible: false,
      addOrUpdateVisible: false,
      generateList: [],
      productList: [],
      isAdd: true,
      classifyList: [],
      classifyIndex: 0,
      productIndex: 0,
    }
  },
  watch: {
    classifyList: {
      handler(newVal) {
        ++this.classifyIndex
      },
    },
    productList: {
      handler(newVal) {
        ++this.productIndex
      },
    },
  },
  computed: {
    dataRule() {
      var validateVersion = (rule, value, callback) => {
        if (value && !isVersion(value)) {
          return callback(new Error('版本号格式错误,输入格式为X.Y.Z'))
        }
        callback()
      }
      return {
        name: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
        versions: [
          { required: true, validator: validateVersion, trigger: 'blur' },
        ],
        classify_ids: [
          {
            type: 'array',
            required: true,
            message: '必选项不能为空',
            trigger: 'change',
          },
        ],
        product_info: [
          {
            type: 'array',
            required: true,
            message: '必选项不能为空',
            trigger: 'change',
          },
        ],
      }
    },
  },
  activated() {
    this.$refs['dataForm'].resetFields()
    this.generateList = []
    this.productList = []
    this.classifyList = []
    this.isAdd = true
    const id = this.$route.params.id
    this.dataForm.id = id
    this.fetchClassifyList()
  },
  methods: {
    handleChange(value) {
      console.log(value)
    },
    treeChange() {
      let arr = []
      let ids = this.dataForm.classify_ids
      if (ids && this.dataForm.classify_ids.length > 0) {
        this.dataForm.classify_ids.forEach((item) => {
          arr.push(item[item.length - 1])
        })
      }

      this.productList = []
      this.dataForm.product_id = ''
      this.dataForm.product_info = []
      if (arr.length < 1) return
      this.fetchProductList(arr)
      console.log(this.dataForm.classify_ids)
    },
    handleDelete(row) {
      const { material_id, id } = row
      let arr = []
      if (this.isAdd || id === 0) {
        arr = this.generateList.filter(
          (item) => item.id !== 0 || item.material_id !== material_id
        )
        this.generateList = arr
      } else {
        this.$confirm(
          '此数据为在线配件数据，此操作将删除该条数据, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(async () => {
            const res = await deleteBomFit({ ids: [id] })
            if (res?.status === 1) {
              this.$message.success(res?.msg || '')
              arr = this.generateList.filter((item) => item.id !== id)
              this.generateList = arr
            }
          })
          .catch(() => {})
      }
    },
    async fetchProductList(id) {
      if (!id) return
      const params = {}
      params.page = 1
      params.num = 99999
      params.classify_ids = id
      const res = await getProductList(params)
      if (res?.status === 1) {
        const list = res?.list || []
        const data = tranSelectArr(list, 'name', 'id', 'sku_list')
        console.log(data)
        data.forEach((item) => {
          item.sku_list.forEach((it) => {
            it.value = it.id
            it.label = it.sku_name
          })
          item.children = item.sku_list
        })
        this.productList = data
        console.log(data)
      }
    },

    // 获取tree
    async fetchClassifyList() {
      const res = await getProductClassify()
      console.log(res)
      if (res?.status === 1) {
        this.classifyList = res.list
        const id = this.dataForm.id || ''
        if (id) {
          this.fetchDetail(id)
          this.isAdd = false
        }
      }
    },
    fitConfirm(row) {
      console.log(row)
      const arr = []
      row.forEach((item) => {
        const { id, material_serial, name, specifications_model } = item
        const temp = {
          parts_num: 1,
          price: null,
          day: null,
          daily_output: null,
          material_id: id,
          id: 0,
          material_serial,
          name,
          specifications_model,
        }
        arr.push(temp)
      })
      console.log(this.generateList)
      console.log(arr)
      this.generateList = [...this.generateList, ...arr]
    },
    handleClose() {
      this.addOrUpdateVisible = false
    },
    handleClose() {
      this.addOrUpdateVisible = false
    },
    handleAdd() {
      this.addOrUpdateVisible = true
    },
    async fetchDetail(id) {
      const params = {
        id,
      }
      const res = await getBomDetail(params)
      if (res?.status === 1) {
        const data = res?.data || {}
        const {
          bom_sub,
          classify_ids,
          product_id,
          product_sku_id,
          ...info
        } = data
        this.dataForm = info
        this.generateList = bom_sub
        if (!classify_ids) return
        const ids = classify_ids.split(',')
        let arr = []
        for (let i = 0; i < ids.length; i++) {
          let data = transCascader(ids[i], this.classifyList)
          arr.push(data)
        }
        this.dataForm.classify_ids = arr

        this.dataForm.product_info = [product_id, product_sku_id]

        this.fetchProductList(ids)
      }
    },
    goBack() {
      this.$router.go(-1)
    },

    // 表单提交
    dataFormSubmitHandle: debounce(
      function() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (!valid) {
            return false
          }
          const params = {}
          const {
            name,
            remarks,
            versions,
            classify_ids,
            product_info,
          } = this.dataForm
          console.log(this.dataForm.product_sku_id)
          params.name = name
          let temp = []
          classify_ids.forEach((item) => {
            temp.push(item[item.length - 1])
          })
          params.classify_ids = temp
          params.remarks = remarks
          const product_id = product_info[0]
          const product_sku_id = product_info[1]
          params.product_id = product_id
          params.product_sku_id = product_sku_id
          params.versions = versions
          params.id = this.dataForm.id ? this.dataForm.id : 0
          const arr = []
          this.generateList.forEach((item) => {
            arr.push({
              id: item.id,
              material_id: item.material_id,
              parts_num: item.parts_num,
              price: item.price,
              day: item.day,
              daily_output: item.daily_output,
            })
          })
          params.bom_sub = arr
          console.log(params)
          const res = await addBom(params)
          if (res?.status === 1) {
            this.$message.success(res?.msg || '操作成功')
            this.$refs['dataForm'].resetFields()
            this.$router.go(-1)
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
  // watch: {
  //   'dataForm.type' (val) {
  //     this.$refs['dataForm'].clearValidate()
  //   }
  // },
}
</script>

<style lang="scss" scoped>
.add-wrapper {
  background: #fff;
  padding: 20px;
  ::v-deep .el-page-header__title {
    font-size: 12px;
  }

  ::v-deep .el-page-header__content {
    font-size: 12px;
  }
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  .form-wrapper {
    ::v-deep .el-select {
      width: 100%;
    }

    .top-form {
      width: 50%;
      margin-top: 36px;

      .picDes {
        margin-top: 12px;
        font-size: 12px;
        color: #999;
        line-height: 18px;
      }
    }
  }
}
</style>
